import Taro, {useState, useEffect} from '@tarojs/taro'
import {View, Text, Image, Canvas, Button} from '@tarojs/components'
import './index.scss'
import env from '../../utils/env.json'
import CanvasPageContext from '../operCanvasPage'

function CanvasPage(props) {
  if (props && Object.keys(props).length > 0) {
  }
  const {source, visible, titleBg} = props
  const canvasDataContext = Taro.useContext(CanvasPageContext)
  const [tempCode, setTempCode] = useState('')
  const [loadPoster, setLoadPoster] = useState(false)
  const [poster, sePoster] = useState()
  const [rejectAuth, setRejectAuth] = useState(false)
  const [canvasHeight, setCanvasHeight] = useState(1)
  const addPic = url => {
    // Taro.showLoading({
    //   title: "图片生成中",
    //   icon: "none",
    //   duration: 1500
    // });
    let windowWidth, ratio
    // eslint-disable-next-line @typescript-eslint/no-this-alias
    const that = this
    if (process.env.TARO_ENV == 'h5') {
      // const ctx = Taro.createCanvasContext("myCanvas", this);
      // ctx.setFillStyle("#FC5074");
      // ctx.fillRect(1, 1, 300, 1200);
      // // var imgBg = new Image();
      // const imgBg = document.createElement('img')
      // imgBg.setAttribute("crossOrigin",'Anonymous');
      // imgBg.src = title;
      // imgBg.onload = function(){
      //   console.log(imgBg,'imgBg')
      //   ctx.drawImage(imgBg, 20, 20, 460, 88);
      // }
      // ctx.draw();
    } else if (process.env.TARO_ENV == 'weapp') {
      let self = this
      let height = canvasHeight
      const ctx = Taro.createCanvasContext('myCanvas', that.$scope)
      ctx.setFillStyle('#FC5074')
      ctx.fillRect(1, 1, 380, 2400)
      Taro.getSystemInfo({
        success: res => {
          windowWidth = res.windowWidth
          ratio = windowWidth / 750
        },
      })
      let title = props.source.seekingContent
      Taro.downloadFile({
        url: 'https://sl-mo.yryz.com/static/img/waterFall.8b365fd.png',
        success: function(res) {
          console.log(res, 'res')
          console.log(props, 'titleBg')
          Taro.downloadFile({
            url: 'https://sl-mo.yryz.com/static/imgs/title.png',
            success: function(titleResult) {
              ctx.drawImage(titleResult.tempFilePath, 150 - 115, 2, 230, 44)
              ctx.setFontSize(12)
              ctx.setFillStyle('#FC5074')
              ctx.fillText(
                props.source.seekingDescription,
                150 - ctx.measureText(props.source.seekingDescription).width * 0.5,
                30,
              )
              let lineCloum = Math.ceil(title.length / 18)
              let ostrtxt = ''
              let olinenum = 0
              let oarrtxt = []
              ctx.setFontSize(12)
              ctx.setFillStyle('#fff')
              ctx.setTextAlign('left')
              for (let i = 0; i < title.length; i++) {
                ostrtxt = ostrtxt + title[i]
                let ometricsw = ctx.measureText(ostrtxt) //计算字符宽度
                if (ometricsw.width > 260) {
                  //设置每行的宽度
                  olinenum++
                  oarrtxt = oarrtxt.concat([ostrtxt])
                  ostrtxt = ''
                }
              }
              oarrtxt = oarrtxt.concat([ostrtxt])
              for (let i = 0; i < oarrtxt.length; i++) {
                ctx.fillText(oarrtxt[i], 20, 70 + i * 24)
              }

              height = oarrtxt.length == 1 ? oarrtxt.length * 26 + 60 : oarrtxt.length * 26 + 40
              ctx.drawImage(res.tempFilePath, 0, 0, 300, 120, 0, 0, 300, 120)
              if (props.source.userPhoto) {
                Taro.downloadFile({
                  url: props.source.userPhoto,
                  success: function(result) {
                    Taro.getImageInfo({
                      src: result.tempFilePath,
                      success: function(data) {
                        console.log(result.tempFilePath, 'result.tempFilePath')
                        ctx.fillRect(18, height - 2, 264, (260 / data.width) * data.height + 4)
                        ctx.drawImage(
                          result.tempFilePath,
                          20,
                          height,
                          260,
                          (260 / data.width) * data.height,
                        )
                        // 绘制圆角
                        // borderRadius(
                        //   ctx,
                        //   16,
                        //   height - 6,
                        //   266,
                        //   (260 / data.width) * data.height + 8,
                        //   8,
                        // )
                        ctx.restore()
                        setCanvasHeight((260 / data.width) * data.height + height + 75)
                        ctx.beginPath()
                        ctx.setFillStyle('rgba(0,0,0,0.4)')
                        ctx.fillRect(0, (260 / data.width) * data.height + height + 20, 300, 55)
                        ctx.setFillStyle('#fff')
                        ctx.setFontSize(12)
                        ctx.fillText('拾恋e生', 60, (260 / data.width) * data.height + height + 40)
                        ctx.setFillStyle('#fff')
                        ctx.setFontSize(14)
                        ctx.fillText(
                          '脱单路上，有我陪伴',
                          60,
                          (260 / data.width) * data.height + height + 58,
                        )

                        Taro.downloadFile({
                          url: 'https://sl-mo.yryz.com/static/imgs/icon2.png',
                          success: function(logo) {
                            console.log(logo, 'logo')
                            ctx.drawImage(
                              logo.tempFilePath,
                              250,
                              (260 / data.width) * data.height + height + 26,
                              40,
                              40,
                            )

                            Taro.downloadFile({
                              url: `${env.httpBaseUrl}/lovelorn-user/v1.3/pb/wx-mini-program/qrcode/lovelorn/unlimited?scene=${source.kid}&width=80&isHyaline=true`,
                              success: function(codeRes) {
                                setTempCode(() => {
                                  return codeRes.tempFilePath
                                })
                                ctx.drawImage(
                                  codeRes.tempFilePath,
                                  10,
                                  (260 / data.width) * data.height + height + 26,
                                  40,
                                  40,
                                )
                                ctx.closePath()
                                ctx.draw(true, () => {
                                  const self = this
                                  Taro.canvasToTempFilePath(
                                    {
                                      x: 0,
                                      y: 0,
                                      width: 320,
                                      height: (260 / data.width) * data.height + height + 75,
                                      destWidth: 640,
                                      destHeight:
                                        ((260 / data.width) * data.height + height + 75) * 2,
                                      fileType: 'png',
                                      quality: 1,
                                      canvasId: 'myCanvas',
                                      success: function(resultdata) {
                                        //调取小程序当中获取图片
                                        sePoster(() => {
                                          return resultdata.tempFilePath
                                        })
                                        // console.error(result.tempFilePath,'111')
                                        console.log(
                                          resultdata.tempFilePath,
                                          canvasHeight,
                                          'canvasHeight',
                                        )
                                        // Taro.hideLoading()
                                      },
                                      fail: function(ex) {
                                        console.error(ex, 'result')
                                      },
                                    },
                                    that.$scope,
                                  )
                                })
                              },
                              fail: function() {
                                console.warn('图片下载失败')
                              },
                            })
                          },
                        })
                      },
                    })
                  },
                })
              } else {
                console.log(height + 75, 'height + 75')
                setCanvasHeight(height + 75)
                ctx.beginPath()
                ctx.setFillStyle('rgba(0,0,0,0.4)')
                ctx.fillRect(0, height + 20, 300, 55)
                ctx.setFillStyle('#fff')
                ctx.setFontSize(12)
                ctx.fillText('拾恋e生', 60, height + 40)
                ctx.setFillStyle('#fff')
                ctx.setFontSize(14)
                ctx.fillText('脱单路上，有我陪伴', 60, height + 58)
                Taro.downloadFile({
                  url: 'https://sl-mo.yryz.com/static/imgs/icon2.png',
                  success: function(logo) {
                    console.log(logo, 'logo')
                    ctx.drawImage(logo.tempFilePath, 250, height + 26, 40, 40)
                    ctx.drawImage(logo.tempFilePath, 10, height + 26, 40, 40)
                    ctx.closePath()
                    ctx.draw(true, () => {
                      const self = this
                      Taro.canvasToTempFilePath(
                        {
                          x: 0,
                          y: 0,
                          width: 320,
                          height: height + 75,
                          destWidth: 640,
                          destHeight: (height + 75) * 2,
                          fileType: 'png',
                          quality: 1,
                          canvasId: 'myCanvas',
                          success: function(result) {
                            //调取小程序当中获取图片
                            sePoster(() => {
                              return result.tempFilePath
                            })
                            // console.error(result.tempFilePath,'111')
                            console.log(result.tempFilePath, canvasHeight, 'canvasHeight')
                            // Taro.hideLoading()
                          },
                          fail: function(ex) {
                            console.error(ex, 'result')
                          },
                        },
                        that.$scope,
                      )
                    })
                  },
                })
              }
            },
          })
        },
        fail: function(ex) {
          console.log('图下载失败', ex)
        },
      })
    }
  }

  // 绘制圆角
  const borderRadius = (ctx, x, y, w, h, r) => {
    // ctx.beginPath()
    // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
    // 这里是使用 fill 还是 stroke都可以，二选一即可
    // ctx.setFillStyle('transparent')
    ctx.setStrokeStyle('transparent')
    // 左上角
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

    // border-top
    ctx.moveTo(x + r, y)
    ctx.lineTo(x + w - r, y)
    ctx.lineTo(x + w, y + r)
    // 右上角
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

    // border-right
    ctx.lineTo(x + w, y + h - r)
    ctx.lineTo(x + w - r, y + h)
    // 右下角
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

    // border-bottom
    ctx.lineTo(x + r, y + h)
    ctx.lineTo(x, y + h - r)
    // 左下角
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

    // border-left
    ctx.lineTo(x, y + r)
    ctx.lineTo(x + r, y)
    // ctx.clip();
    // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
    // ctx.fill()
    ctx.stroke()
    // ctx.closePath()
    //
    // 剪切
  }

  // useEffect(() => {
  //   if (Object.keys(source).length > 0) {
  //     Taro.downloadFile({
  //       url: `${env.httpBaseUrl}/gateway/lovelorn-user/v1.3/pb/wx-mini-program/qrcode/unlimited?scene=${source.kid}&width=80`,
  //       success: function(res) {
  //         setTempCode(() => {
  //           return res.tempFilePath
  //         })
  //       },
  //       fail: function() {
  //         console.warn('图片下载失败')
  //       },
  //     })
  //   }
  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  // }, [])
  const savePic = () => {
    Taro.showLoading({
      title: '图片生成中',
      icon: 'none',
      duration: 1500,
    })
    if (!rejectAuth) {
      if (poster) {
        Taro.saveImageToPhotosAlbum({
          filePath: poster,
          success(res) {
            console.log(res)
            Taro.showModal({
              title: '存图成功',
              content: '图片成功保存到相册了，去发圈噻~',
              showCancel: false,
              confirmText: '好哒',
              confirmColor: '#72B9C3',
              success: function(result) {
                setLoadPoster(false)
                // setVisible(false)
                if (result.confirm) {
                  // console.log('用户点击确定');
                }
              },
            })
          },
          fail: function(ex) {
            setRejectAuth(true)
            console.warn(ex)
            Taro.showToast({
              title: '保存相册失败！',
              icon: 'none',
              duration: 3000,
            })
          },
        })
      }
    } else {
      //    重新授权
      Taro.openSetting({
        success: function(res) {
          console.log(res, 'wadd')
          if (res.authSetting) {
            if (res.authSetting['scope.writePhotosAlbum'] == true) {
              setRejectAuth(false)
            }
          } else {
            Taro.showToast({
              title: '获取用户权限失败',
              icon: 'none',
            })
          }
        },
      })
    }
  }
  return (
    <View className="canvasPage">
      {loadPoster && (
        <Canvas
          style={{
            width: '300px',
            height: canvasHeight + 'px',
            margin: '0 auto',
            transform: 'translateX(-1200px)',
          }}
          id="canvasId"
          canvasId="myCanvas"></Canvas>
      )}

      {visible && (
        <View className="hideCanvas">
          <View className="bottomFixed">
            <View className="flex shareTop">
              <Text className="shareT">分享</Text>
              <Image
                className="closecanvas"
                onClick={() => {
                  props.hidePoster()
                }}
                src={require('../../assets/close.png')}
              />
            </View>
            <View className="flex">
              <View className="weixin">
                <Button openType="share" className="shreButton">
                  <View className="shareDiv">
                    <Image className="sharewxImg" src={require('../../assets/wechat.png')} />
                  </View>
                </Button>
                <View>微信好友</View>
              </View>
              <View
                className="quan"
                onClick={() => {
                  addPic(tempCode)
                  setLoadPoster(true)
                  props.hidePoster()
                  // setVisible(false)
                }}>
                <Button className="shreButton">
                  <View className="shareDiv">
                    <Image className="sharewxImg" src={require('../../assets/pengyouquan.png')} />
                  </View>
                </Button>
                <View>生成海报</View>
              </View>
            </View>
          </View>
        </View>
      )}
      {loadPoster && (
        <View
          className="hideCanvas"
          onClick={() => {
            props.hidePoster()
            setLoadPoster(false)
          }}>
          <View className="handle hidePoster" style={{background: `${source.background}`}}>
            <View className="handleWrap" style={{position: 'relative'}}>
              <View
                className="flex shareTop"
                style={{justifyContent: 'flex-end'}}
                onClick={() => {
                  savePic()
                }}>
                <Image src={require('../../assets/seeking/download.png')} className="closecanvas" />
              </View>
              <View className="posterTitle">{props.source.seekingDescription}</View>
              <View className="posterContent">
                <Text> {props.source.seekingContent}</Text>
              </View>
              {props.source.userPhoto && (
                <View className="poster-wrap">
                  <Image src={props.source.userPhoto} mode="widthFix" className="poster-img" />
                </View>
              )}

              <View className="fixed-btn flex">
                <Image
                  src={`${env.httpBaseUrl}/gateway/lovelorn-user/v1.3/pb/wx-mini-program/qrcode/lovelorn/unlimited?scene=${props.source.kid}&width=80&isHyaline=true`}
                  className="flexCode"
                />
                <View className="flexText flex-1">
                  <View className="flexLineTop">脱单e生</View>
                  <View className="flexLineBottom">脱单路上 有我陪伴</View>
                </View>
                <Image src={require('../../assets/seeking/icon.png')} className="flexLogo" />
              </View>
            </View>
          </View>
        </View>
      )}
    </View>
  )
}

export default CanvasPage
